package org.arkeologgr.appening.dataacess;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;

import com.google.android.maps.GeoPoint;

public class GPSDataManager {
	
	private static GPSDataManager instance;
	LocationManager mLocationManager;
	
	public static void setup(Context context){
		instance = new GPSDataManager(context);
		
	}
	
	public static void tearDown(){
		instance = null;
	}
	
	public GPSDataManager(Context context){
		mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
	}
	
	public static GPSDataManager getInstance()
	{
		if(instance == null){
			throw new IllegalStateException(
			"GPSDataManager.setup() must be called before accessing GPSDataManager.getInstance()");
		}
		return instance;
	}

	//TODO: The gps data manager should manage the location handling, not only be a global container
	public GeoPoint getMyCurrentLocation() {
			
		Criteria criteria = new Criteria();
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_HIGH);
	
		String provider;
		if (mLocationManager.getBestProvider(criteria, true) != null) {
		    provider = mLocationManager.getBestProvider(criteria, true);
		} else {
		    provider = mLocationManager.getBestProvider(criteria, false);
		}
		
		Location loc = null;
		if(provider != null){
			loc = mLocationManager.getLastKnownLocation(provider);
		}
	
		if (loc != null) {
		    if (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) {
		 
			return new GeoPoint(
				(int) (loc.getLatitude() * 1E6), (int) (loc
					.getLongitude() * 1E6));
		    }
		}
		return null;
	}
}
